package com.skyable.auth.config.security.filter;

import com.skyable.auth.entity.SysUser;
import com.skyable.auth.service.IPermissionService;
import com.skyable.auth.service.IUserService;
import com.skyable.auth.utils.RedisUtil;
import com.skyable.common.common.ServiceResult;
import com.skyable.common.constants.redis.RedisKeyConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author GaoYuan
 * @title: VerificationCodeManager
 * @projectName spring-cloud-oauth2-demo
 * @description: TODO
 * @date 2021/4/1317:01
 */
@Component
public class VerificationCodeManager extends BaseManager implements AuthenticationManager {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.getName() != null && authentication.getCredentials() != null) {
            String phone = authentication.getName();
            String verityCode = (String) authentication.getCredentials();
            if(RedisUtil.hasKey(RedisKeyConstants.USER_VERITY_CODE_KEY + phone)) {
                String redisVerityCode = RedisUtil.get(RedisKeyConstants.USER_VERITY_CODE_KEY + phone);
                if(verityCode.equals(redisVerityCode)) {
                    ServiceResult<SysUser> serviceResult = userService.getUserByPhoneNum(phone);
                    if(serviceResult.getSuccess()) {
                        SysUser sysUser = serviceResult.getResult();
                        if(sysUser != null) {
                            List<GrantedAuthority> authorityList = getUserAuthorityList(sysUser.getUsername());
                            return new UsernamePasswordAuthenticationToken(new org.springframework.security.core.userdetails.User(
                                    sysUser.getUsername(),
                                    sysUser.getPassword(),
                                    authorityList), sysUser.getPassword(), authorityList);
                        }
                    }
                }
            }
        }
        throw new BadCredentialsException("Bad Credentials");
    }
}
